package service

import (
	"math"
	"strconv"
	"strings"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/model"
	. "zimuzu_cvn_web_api/pkg/e"
)

//保存通知
func SaveTransferNotice(postData model.CoboTransaction) bool {
	var data model.TransferNotice
	//数据处理
	data.NoticeId = postData.Id
	data.Coin = postData.Coin
	data.AbsAmount, _ = strconv.ParseFloat(postData.AbsAmount, 64)
	data.Amount, _ = strconv.ParseInt(postData.Amount, 10, 64)
	data.Decimal = postData.Decimal
	data.From = postData.SourceAddress
	data.To = postData.Address
	data.TxId = postData.TxId
	data.TransStatus = postData.Status
	//参数校验
	if data.AbsAmount <= 0 || data.Amount <= 0 || data.Decimal <= 0 {
		return false
	}
	if data.NoticeId == "" || data.Coin == "" || data.To == "" {
		return false
	}
	//检测是否为充值通知
	if postData.Side != "deposit" {
		return true
	}
	//检查NoticeId是否存在
	ok, err := model.ExistTransferNoticeId(config.C.DB.DB, data.NoticeId)
	if err != nil {
		return false
	}
	if ok {
		return true
	}
	//检查TxId是否存在
	ok, err = model.ExistTransferNoticeTxId(config.C.DB.DB, data.TxId)
	if err != nil {
		return false
	}
	if ok {
		return true
	}
	//保存通知
	if err = model.AddTransferNotice(config.C.DB.DB, data); err != nil {
		return false
	}
	return true
}

//提现确认
func ComfirmTransfer(postData model.CoboTransaction) bool {
	var id int64
	if postData.RequestId == "" || postData.Coin == "" || postData.Address == "" {
		return false
	}
	//检测是否为提现
	if postData.Side != "withdraw" {
		return true
	}
	//解析id
	if ok := strings.Contains(postData.RequestId, "_"); ok {
		strs := strings.Split(postData.RequestId, "_")
		idStr := strs[len(strs)-1]
		id, _ = strconv.ParseInt(idStr, 10, 64)
	} else {
		idStr := postData.RequestId
		id, _ = strconv.ParseInt(idStr, 10, 64)
	}
	//获取转账日志
	amount, _ := strconv.ParseFloat(postData.AbsAmount, 64)
	if postData.Coin == COIN_NAME_CVNT {
		cvnLog, err := model.GetCvnLog(config.C.DB.DB, id)
		if err != nil {
			return false
		}
		if cvnLog.To != postData.Address {
			return false
		}
		if ok := FloatEqual(math.Abs(cvnLog.Amount), amount, COIN_DECIMAL_CVNT+1); !ok {
			return false
		}
	} else if postData.Coin == COIN_NAME_USDT {
		usdtLog, err := model.GetUsdtLog(config.C.DB.DB, id)
		if err != nil {
			return false
		}
		if usdtLog.To != postData.Address {
			return false
		}
		if ok := FloatEqual(math.Abs(usdtLog.Amount), amount, COIN_DECIMAL_CVNT+1); !ok {
			return false
		}
	} else {
		return false
	}
	return true
}
